import React, {Component} from 'react';
import QuoteForm from './Form.js';
import {Button, Tabs, Spin} from 'antd';
import {message} from 'antd';
import {isBlank} from "../util/util";
import QuoteTable from "../utilComponent/Table";
import {API_URL} from "../constants";

const ZOHO = window.ZOHO;
const dateFormat = 'YYYY-MM-DD';

class App extends Component {
    constructor(props) {
        super(props);
        this.formRef = React.createRef();
        this.quoteTableRef = React.createRef();

        this.state = {
            activeKey: '1',
            Account: {}, // 存储FcontractNo的值
            formData: {},
            user: {},
            loading: false,
            quoteDetail: [],
        };
    }

    async componentDidMount() {
        let user = {};
        let quoteDetail = [];
        await ZOHO.CRM.CONFIG.getCurrentUser().then(function (data) {
            user = data.users[0]
        });
        if (!isBlank(window.id)) {
            let req_data = {
                parameters: {},
                method: "GET",
                url: API_URL + `/crm/v3/Quotationsdetail/search?criteria=(Quotations.id:equals:${window.id})`,
                param_type: 1,
            };
            await ZOHO.CRM.CONNECTION.invoke("crm", req_data).then((data) => {
                quoteDetail = data.details.statusMessage.data;
            });
        }
        console.log(quoteDetail)
        this.setState({user: user, quoteDetail: quoteDetail});

    }

    onChange = (activeKey) => {
        if (activeKey === '2') {
            const formInstance = this.formRef.current;
            const formData = formInstance.formRef.current;
            let Account = formData.getFieldValue('Account');
            console.log(Account)
            if (isBlank(Account)) {
                message.error('请先选择客户');
                return
            }
            let Companyletterhead = formData.getFieldValue('Companyletterhead');
            console.log(Companyletterhead)
            if (isBlank(Companyletterhead?.value)) {
                message.error('请先选择发货人代码');
                return
            }
            this.setState({activeKey, Account, formData}); // 更新activeKey和FcontractNo的值
        }
        this.setState({activeKey});
    };
    getRate = () => {
        const formInstance = this.formRef.current;
        const current = formInstance.formRef.current;
        if (isBlank(current.getFieldValue("Exchangerate")) || current.getFieldValue("Exchangerate") === 0) {
            return 1;
        }
        return current.getFieldValue("Exchangerate");
    }
    handleSave = () => {
        this.setState({loading: true})
        try {
            console.log(new Date().getTime())
            const {user, quoteDetail} = this.state
            const formInstance = this.formRef.current;
            const current = formInstance.formRef.current;
            const quoteTableInstance = this.quoteTableRef.current;
            const quoteTableData = quoteTableInstance.state.data;
            console.log(quoteTableData)
            current.validateFields().then((values) => {
                values.Dateofinvoice = values.Dateofinvoice?.format('YYYY-MM-DD');
                values.Quotationvalidityperiod = values.Quotationvalidityperiod?.format('YYYY-MM-DD');
                values.Account = {
                    id: values.Account?.value,
                    name: values.Account?.label
                }
                if (isBlank(values.Accountcontactperson?.value)) {
                    delete values.Accountcontactperson;
                } else {
                    values.Accountcontactperson = {
                        id: values.Accountcontactperson?.value,
                        name: values.Accountcontactperson?.label
                    }
                }

                if (isBlank(values.Companyletterhead?.value)) {
                    delete values.Companyletterhead;
                } else {
                    values.Companyletterhead = {
                        id: values.Companyletterhead?.value,
                        name: values.Companyletterhead?.label
                    }
                }
                if (isBlank(values.DestinationPort?.value)) {
                    delete values.DestinationPort;
                } else {
                    values.DestinationPort = {
                        id: values.DestinationPort?.value,
                        name: values.DestinationPort?.label
                    }
                }
                if (isBlank(values.Currencys?.value)) {
                    delete values.Currencys;
                } else {
                    values.Currencys = {
                        id: values.Currencys?.value,
                        name: values.Currencys?.label
                    }
                }
                if (isBlank(values.LoadingPort?.value)) {
                    delete values.LoadingPort;
                } else {
                    values.LoadingPort = {
                        id: values.LoadingPort?.value,
                        name: values.LoadingPort?.label
                    }
                }
                if (isBlank(values.Deals?.value)) {
                    delete values.Deals;
                } else {
                    values.Deals = {
                        id: values.Deals?.value,
                        name: values.Deals?.label
                    }
                }
                let config = {
                    Entity: "Quotations",
                    APIData: [values],
                    Trigger: ["workflow"]
                }
                console.log(user?.id)
                let errorMessage = "";
                quoteTableData.map((item, index) => {
                    if (isBlank(item.AccountprtNo)) {
                        errorMessage += `${index + 1} 行未填写客户货号`
                    }
                })
                if (!isBlank(errorMessage)) {
                    message.error(errorMessage)
                    return;
                }
                if (window.id !== undefined) {
                    values.id = window.id;
                    console.log(config);

                    ZOHO.CRM.API.updateRecord(config)
                        .then(function (data) {
                            console.log(data)
                            if (data.data[0].status === "success") {
                                message.success("保存成功");
                                let inserts = [];
                                let updates = [];
                                // quoteDetail 中de的id有，quoteTableData 没有id，说明被删掉了
                                let deletes = quoteDetail.filter(item => !quoteTableData.some(data => data.id === item.id))
                                    .map(item => item.id);
                                console.log(deletes)
                                quoteTableData.map((item, index) => {
                                    item.Quotations = {
                                        id: window.id,
                                        name: values.Name
                                    }
                                    if (isBlank(item.AccountprtNo)) {
                                        message.error("")
                                    }
                                    if (item.Unit?.id === "" || item.Unit?.id === undefined) {
                                        item.Unit = null;
                                    }
                                    item.Owner = {id: user.id}
                                    if (isBlank(item?.id)) {
                                        delete item.id;
                                        inserts.push(item)
                                    } else {
                                        updates.push(item)
                                    }
                                })
                                if (inserts.length > 0) {
                                    let req_data = {
                                        "parameters": {
                                            data: inserts
                                        },
                                        "headers": {},
                                        "method": "POST",
                                        "url": API_URL + `/crm/v3/Quotationsdetail`,
                                        "param_type": 2
                                    };
                                    ZOHO.CRM.CONNECTION.invoke("crm", req_data).then(function (data) {
                                        console.log(data);
                                    });
                                }
                                if (updates.length > 0) {
                                    let req_data = {
                                        "parameters": {
                                            data: updates
                                        },
                                        "headers": {},
                                        "method": "PUT",
                                        "url": API_URL + `/crm/v3/Quotationsdetail`,
                                        "param_type": 2
                                    };
                                    ZOHO.CRM.CONNECTION.invoke("crm", req_data).then(function (data) {
                                        console.log(data);
                                    });
                                }
                                if (deletes.length > 0) {
                                    let req_data = {
                                        "parameters": {},
                                        "headers": {},
                                        "method": "DELETE",
                                        "url": API_URL + `/crm/v3/Quotationsdetail?ids=${deletes}&wf_trigger=true`,
                                        "param_type": 2
                                    };
                                    ZOHO.CRM.CONNECTION.invoke("crm", req_data).then(function (data) {
                                        console.log(data);
                                    });
                                }
                                ZOHO.CRM.UI.Record.open({Entity: "Quotations", RecordID: window.id})
                                    .then(function (data) {
                                        console.log(data)
                                    })

                            } else {
                                message.error("保存失败");
                            }
                        })
                } else {
                    ZOHO.CRM.API.insertRecord(config).then(function (data) {
                        console.log(data)
                        let id = data.data[0].details.id;
                        quoteTableData.map(item => {
                            item.Quotations = {
                                id: id,
                                name: values.Name
                            }
                            if (item.Unit?.id === "" || item.Unit?.id === undefined) {
                                item.Unit = null;
                            }
                            item.Owner = {id: user?.id}
                            delete item.id;
                        })
                        let req_data = {
                            "parameters": {
                                data: quoteTableData
                            },
                            "headers": {},
                            "method": "POST",
                            "url": API_URL + `/crm/v3/Quotationsdetail`,
                            "param_type": 2
                        };
                        ZOHO.CRM.CONNECTION.invoke("crm", req_data).then(function (data) {
                            console.log(data);
                        });
                        message.success("保存成功");
                        ZOHO.CRM.UI.Record.open({Entity: "Quotations", RecordID: id})
                            .then(function (data) {
                                console.log(data)
                            })
                    });
                }
                console.log(values)

            }).catch(e => {
                console.log(e);
            })

        } catch (e) {
            message.error(e)
        } finally {
            setTimeout(() => {
                this.setState({loading: false});
            }, 2000);
        }


    };
    updateTotal = (sumData) => {
        // const {current} = this.formRef;
        // console.log(sumData)
        // Object.entries(sumData)?.map(([key, value]) => {
        //     current.setFieldValue(key, value)
        // })
    }

    render() {
        const {activeKey, loading} = this.state;

        return (
            <div>
                <Spin spinning={loading}>
                    <div style={{display: 'flex', justifyContent: 'flex-end', marginBottom: 16}}>
                        {activeKey === '2' && (
                            <div>
                                <Button disabled={loading} onClick={this.handleSave} type="primary"
                                        style={{marginRight: 10}}>
                                    保存
                                </Button>
                                <Button style={{marginLeft: 8, marginRight: 8}} onClick={this.handleCancel}>
                                    取消
                                </Button>
                            </div>
                        )}
                    </div>
                    <Tabs defaultActiveKey="1" centered activeKey={activeKey} onChange={this.onChange}>
                        <Tabs.TabPane tab="主要内容" key="1">
                            <QuoteForm ref={this.formRef}/>
                        </Tabs.TabPane>
                        <Tabs.TabPane tab="报价明细" key="2">
                            <QuoteTable ref={this.quoteTableRef} parentModuleName="Quotations"
                                        getRate={this.getRate}
                                        updateTotal={this.updateTotal}
                                        template="quoteTemplate"
                                        paste={true} moduleName="Quotationsdetail" jsonName="quotetableconf.json"/>
                        </Tabs.TabPane>
                    </Tabs>
                </Spin>

            </div>

        );
    }
}

export default App;